// pages/homework/bonusPoints/bonusPoints.js
import https from '../../../utils/request4.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    examId: null,
    title: null,
    gradeid: null,
    courseid: null,
    classId: null,
    options: [],
    selectedValue: {},
    showDropdown: false,
    examCourseId: null,
    studentTestQuestions: [],
    testQuestioninformation: {},
    selectPageInfo: {},
    targetX: 0,   // movable-view 初始 x 坐标
    targetY: 0,   // movable-view 初始 y 坐标
    scrollTop: 0, // scroll-view 滚动位置
    scrollLeft: 0,
    containerWidth: 0,  // movable-area 的实际宽度
    containerHeight: 0, // movable-area 的实际高度
    imgWidth: 0,        // 图片原始宽度
    imgHeight: 0,       // 图片原始高度
    croppedImagePath: null,
  },
  // 图片加载完成后触发
  onImageLoad(e) {
    const { width: imgWidth, height: imgHeight } = e.detail;
    const query = wx.createSelectorQuery().in(this);

    // 获取 movable-area 的实际尺寸
    query.select('.movable-area').boundingClientRect(rect => {
      const containerWidth = rect.width;
      const containerHeight = rect.height;
        console.log(containerWidth,containerHeight,'===========-----------------++++++++++++++++++++');
      // 计算图片在 aspectFit 模式下的实际显示尺寸
      const scale = Math.min(
        containerWidth / imgWidth, 
        containerHeight / imgHeight
      );
      const displayWidth = imgWidth * scale;
      const displayHeight = imgHeight * scale;

      // 计算目标点 (200, 300) 在容器中的坐标
      const targetX = 200 * scale;
      const targetY = 250 * scale;

      // 计算需要设置的 movable-view 的 x 和 y
      // 公式：容器中心坐标 - 目标点坐标
      const newX = (containerWidth / 2 - targetX);
      const newY = (containerHeight / 2 - targetY);
        console.log(newX,newY,'777777777777777777777777');
      this.setData({
        targetX: newX,
        targetY: newY,
        containerWidth,
        containerHeight,
        imgWidth,
        imgHeight,
      });
    }).exec();
  },
  cropImage(imagePath) {
    const ctx = wx.createCanvasContext('cropCanvas');
    const targetX = this.data.testQuestioninformation.x;
    const targetY = this.data.testQuestioninformation.y;
    const cropWidth = this.data.testQuestioninformation.w;
    const cropHeight = this.data.testQuestioninformation.h;

    ctx.drawImage(
      imagePath,
      targetX, targetY,
      cropWidth, cropHeight,
      0, 0,
      cropWidth, cropHeight
    );

    // 必须调用 ctx.draw 并等待回调
    ctx.draw(false, () => {
      wx.canvasToTempFilePath({
        canvasId: 'cropCanvas',
        success: (res) => {
          this.setData({ croppedImagePath: res.tempFilePath });
        },
        fail: (err) => {
          console.error('导出失败', err);
        }
      });
    });
  },
  toggleDropdown() {
    this.setData({
      showDropdown: !this.data.showDropdown
    });
  },
  selectItem(e) {
    const value = e.currentTarget.dataset.value;
    this.setData({
      selectedValue: value,
      showDropdown: false
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
        // examId: options.examId,
        // title: options.title,
        // gradeid: options.gradeid,
        // courseid: options.courseid,
        // classId: options.classId
        examCourseId: options.examCourseId,
      })
    this.getInfo()
  },
  async getInfo() {
        // 获取答题卡异常题目下拉列表
        let options={
            url:'/scoreexception/questionlist?examCourseId='+this.data.examCourseId,
            method:'get',
            header:{"content-type":"application/x-www-form-urlencoded"}
        }
        let res = await https(options)
        if(res&&res.data.code==200){
            this.setData({
                options: res.data.data
            })
            if (res.data.data.length > 0) {
                this.setData({
                    selectedValue: res.data.data[0]
                })
                this.nextQuestion()
            }
        } else {
            wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000 //持续的时间
            })
        }
  },
  async nextQuestion() {
        let data = {
            examCourseId: this.data.examCourseId,
            questionId: this.data.selectedValue.id
        }
        let options={
            url:'/scoreexception/next',
            method:'get',
            data: data,
            header:{"content-type":"application/x-www-form-urlencoded"}
        }
        let res = await https(options)
        if(res&&res.data.code==200){
            this.setData({
                testQuestioninformation: res.data.data
            })
            if (this.data.testQuestioninformation.paperImages.length > 0) {
                this.setData({
                    selectPageInfo: this.data.testQuestioninformation.paperImages[0]
                })
                setTimeout(() => {
                    this.downloadAndCrop(this.data.selectPageInfo.filePath)
                },1000)
            }
            console.log(this.data.testQuestioninformation,'-------------------');
        } else {
            wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000 //持续的时间
            })
        }
  },
  downloadAndCrop(item) {
    wx.downloadFile({
      url: item,
      success: (res) => {
        this.cropImage(res.tempFilePath);
      },
      fail: (err) => {
        console.error('下载失败', err);
      }
    });
  },
  selectPage(e) {
    let item = e.currentTarget.dataset.item
    this.setData({
        selectPageInfo: item
    })
  },
  // 缩放事件处理
  onScale(e) {
    const { scale } = e.detail;
    this.setData({ scale });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})